package org.smile.db.model;


import java.util.ArrayList;
import java.util.List;

/**
 * 这是一个用来封装查询条件的类
 * 
 * 
 * @author strive
 *
 */
public class QueryModel {
	
	private String boolRelation;
	
	private String fromString;
	
	private List params=new ArrayList();
	
	private String resultStr;
	
	private String orderBy;
	
	/**
	 * 构造函数
	 * @param entClass
	 */
	public QueryModel(String fromString){
		this.fromString=fromString;
	}
	
	public void addParam(QueryParam param) {
		if(param.getValue()!=null){
			this.params.add(param);
		}
	}
	/**
	 * 返回结果
	 * 如不指定：则返回默认为*
	 * 如：new map(name as name,age as age)
	 * @param resultStr
	 */
	public void setResultStr(String resultStr) {
		this.resultStr = resultStr;
	}
	/**
	 * 设置查询目标
	 * @param fromString
	 */
	public void setFromString(String fromString) {
		this.fromString = fromString;
	}
	/**
	 * 设置排序 
	 * 如：setOrderBy("name desc ,age")则是先name倒序再age顺序
	 * @param orderBy
	 */
	public void setOrderBy(String orderBy)
	{
		this.orderBy=orderBy;
	}

	/**
	 * 数据查询Query
	 * @param session
	 * @return
	 * @throws Exception 当传入信息不当时 构建查询语句出错
	 */
	public String parseToSql() throws Exception
	{
		
			StringBuffer hqlBuffer=new StringBuffer();
			if(resultStr==null){
				hqlBuffer.append("SELECT * FROM ");
			}else{
				hqlBuffer.append("SELECT ").append(resultStr).append(" FROM ");
			}
			hqlBuffer.append(fromString);
			if(parsParams()==null||"".equals(parsParams().trim()))
			{
				hqlBuffer.append(" WHERE 1=1 ");
			}else{
				hqlBuffer.append(parsParams());
			}
			if(this.orderBy!=null)
			{
				hqlBuffer.append(" ORDER BY ").append(this.orderBy);
			}
			return this.setParameters(hqlBuffer.toString());
	}
	
	/**
	 * toString 方法把些查询控件解析成一条查询语句
	 */
	public String toString()
	{
		try{
			StringBuffer hqlBuffer=new StringBuffer();
			if(resultStr==null){
				hqlBuffer.append("FROM ");
			}else{
				hqlBuffer.append("SELECT ").append(resultStr).append(" FROM ");
			}
			hqlBuffer.append(fromString);
			hqlBuffer.append(parsParams());
			if(this.orderBy!=null)
			{
				hqlBuffer.append(" ORDER BY ").append(this.orderBy);
			}
			return hqlBuffer.toString();
		}
		catch(Exception e)
		{
			return "查询控制器解析出错，请查证";
		}
	}
	/**
	 * 把查询参数 解析查询条件成一个Where字句
	 * @return
	 * @throws Exception 
	 */
	public String parsParams() throws Exception
	{
		StringBuffer paramStr=new StringBuffer();
		//当存在子条件语句关系属性的时候
		//子条件关系 如:boolRelation="#0 and (#1 or #2)"
		//以每一个字句替换 #0 #1 #2 
		if(this.boolRelation!=null&&!"".equals(this.boolRelation.trim()))
		{
			StringBuffer subWhereString=new StringBuffer();
			
			int i=0,size=params.size();
			if(size>0){
				paramStr.append(" WHERE ");
				String temp=new String(boolRelation);
				for(i=0;i<size;i++)
				{
					QueryParam queryParam=(QueryParam)params.get(i);
					if(queryParam.getValue()!=null)
					{
						subWhereString.append(queryParam.getField()).append(" ");
						subWhereString.append(queryParam.getOperate()).append(":");
						if(queryParam.getParam()!=null){
							subWhereString.append(queryParam.getParam());
						}else {
							subWhereString.append(queryParam.getField());
						}
					}
					else{
						throw new Exception("过滤参数的值不能为空,请验证");
					}
					temp=temp.replace("#"+i, subWhereString.toString());
					subWhereString.setLength(0);
				}
				paramStr.append(temp.toString());
			}
		}else {
			//不存在关系属性的时候 默认所有这条件以AND连接
			paramStr=new StringBuffer();
			int i=0,size=params.size();
			if(size>0){
				paramStr.append(" WHERE ");
				for(i=0;i<size;i++)
				{
					QueryParam queryParam=(QueryParam)params.get(i);
					if(queryParam.getOperate().equalsIgnoreCase(QueryParam.IS_NULL)||queryParam.getOperate().equalsIgnoreCase(QueryParam.NOT_NULL))
					{
						paramStr.append(queryParam.getField()).append(" ").append(queryParam.getOperate());
						if(i<size-1){
							paramStr.append(" AND ");
						}
					}else{
						//值不为空时才添加到where子句中
						if(queryParam.getValue()!=null)
						{
							paramStr.append(queryParam.getField()).append(" ");
							paramStr.append(queryParam.getOperate()).append(" :");
							if(queryParam.getParam()!=null){
								paramStr.append(queryParam.getParam());
							}else {
								paramStr.append(queryParam.getField());
							}
							if(i<size-1){
								paramStr.append(" AND ");
							}
						}
					}
					
				}
			}
		}
		return paramStr.toString();
	}
	/**
	 * 设置参数 当没有param时默认以field做为param
	 * @param query
	 */
	private String setParameters(String sql) {
		//循环设置参数的值 参数
		for(int i=0;i<params.size();i++) {
			QueryParam p=(QueryParam)params.get(i);
			if(p.getValue()!=null)
			{
				//当查询参数的value不为空时，才能这个参数添加到where子句中
				 if(p.getParam()!=null)
				 {
					sql=sql.replace(":"+p.getParam(),p.getValue()+"");
				 }else{
					//当没有参数名时，默认以字段名field做为参数名，则设置参数时用field
					 sql=sql.replace(":"+p.getField(), p.getValue()+"");
				 }
			}
		}
		return sql;
	}
	
}
